package com.codeerror.demo.view;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.codeerror.demo.R;
import com.codeerror.demo.util.DateUtil;

public class SelectDateDialog extends Dialog {
    public SelectDateDialog(@NonNull Context context) {
        super(context);
    }

    public static class Builder {
        private final SelectDateDialog dialog;
        private final View layout;

        private final ImageView close;
        private final Button select;
        private final DatePicker dp;

        private long curTime;
        private OnSelectDateListener onSelectDateListener;

        public Builder(Context context) {
            dialog = new SelectDateDialog(context);
            layout = LayoutInflater.from(context)
                    .inflate(R.layout.layout_dialog_select_date, null, false);
            close = layout.findViewById(R.id.iv_dialog_select_date_close);
            select = layout.findViewById(R.id.btn_dialog_select_date);
            dp = layout.findViewById(R.id.dp_dialog_select_date);
        }

        public Builder setOnSelectDateListener(OnSelectDateListener onSelectDateListener) {
            this.onSelectDateListener = onSelectDateListener;
            return this;
        }

        public Builder setCurTime(long curTime) {
            this.curTime = curTime;
            return this;
        }

        public SelectDateDialog create() {
            dialog.setContentView(layout);
            // 设置日历初始日期
            dp.init(DateUtil.getYearOfTime(curTime), DateUtil.getMonthOfTime(curTime) - 1,
                    DateUtil.getDayOfTime(curTime), (datePicker, y, m, d) -> {
                        //  设置日历点击事件，点击更改日期提示信息
                        curTime = DateUtil.getMillis(y, m + 1, d);
                    });
            close.setOnClickListener(view -> dialog.dismiss());
            select.setOnClickListener(view -> {
                if (onSelectDateListener != null) {
                    onSelectDateListener.onSelectDate(curTime);
                }
                dialog.dismiss();
            });
            return dialog;
        }
    }

    /**
     * 展示Dialog，添加Dialog显示和消失的动画
     */
    public void showDialog() {
        Window window = getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        // 缩放显示和消失
        window.setWindowAnimations(R.style.dialogWindowShowAnim);
        // 可按后退键退出，但不可点外边退出
        setCancelable(true);
        setCanceledOnTouchOutside(false);
        show();
    }

    public interface OnSelectDateListener {
        void onSelectDate(long millis);
    }
}
